import { computed, h } from "vue";
import { DashboardOutlined, DashboardFilled, MenuOutlined, SettingFilled, TableOutlined } from "@ant-design/icons-vue";

const cacheMap = new WeakMap();

/**
 * 对props下对象进行包装， 只对对象有效，单属性无效
 * @param props
 * @param propName
 * @param emit
 */
export const useModel = (props: any, propName: string, emit: any) => {
  const emitKey = `update:${propName}`;
  return computed({
    get() {
      if (cacheMap.has(props[propName])) {
        return cacheMap.get(props[propName]);
      }
      const proxy = new Proxy(props[propName], {
        get(target, key) {
          return Reflect.get(target, key);
        },
        set(target, key, value) {
          emit(emitKey, {
            ...target,
            [key]: value
          });
          return true;
        }
      })
      cacheMap.set(props[propName], proxy);
      return proxy
    },
    set(val) {
      emit(emitKey,  val);
    }
  })
}

/**
 * Lightens a 6 char HEX color according to the passed percentage
 * @param {string} color The color to change
 * @param {number} amount The amount to change the color by
 * @returns {string} The processed color represented as HEX
 */
export const lighten = (color: string, amount: number) => {
  if (color) {
    color = color.indexOf('#') >= 0 ? color.substring(1, color.length) : color
    amount = Math.trunc((255 * amount) / 100)
    return `#${addLight(color.substring(0, 2), amount)}${addLight(
        color.substring(2, 4),
        amount
    )}${addLight(color.substring(4, 6), amount)}`
  } else {
    return "";
  }

}

/**
 * Sums the passed percentage to the R, G or B of a HEX color
 * @param {string} color The color to change
 * @param {number} amount The amount to change the color by
 * @returns {string} The processed part of the color
 */
const addLight = (color: string, amount: number) => {
  const cc = parseInt(color, 16) + amount
  const c = cc > 255 ? 255 : cc
  return c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`
}

/*
 * 渲染Icon 需要根据需要重写css样式
 * @param {string} icon 图标名称
 * @return {Function}
 */

export const renderIcon = (icon: string, title?: string) => {
  return () =>
      h('div', { class: 'nx-icon' }, [
        h('i', { class: 'icon iconfont ' + icon }),
        title ? h('div', { class: 'nx-icon-title' }, title ? title : '') : null
      ])
}


export const transformIcon = (icon: string) => {
  switch (icon) {
    case "DashboardOutlined":
      return h(DashboardOutlined);
    case "DashboardFilled":
      return h(DashboardFilled);
    case "SettingFilled":
      return h(SettingFilled);
    case "TableOutlined":
      return h(TableOutlined);
    default:
      return h(MenuOutlined);
  }
}